import {
	defineStore
} from 'pinia'
import {
	convertToTree,
	flattenTree,
	handleCheckBoxChecked,
	handleSelectedPopup,
	mapToArr,
	selectedTypeNumComputed,
	SELECT_PAGE_TYPE
} from '../../utils/util'


import _ from 'lodash'
import {
	FormTeamStoreKey,
} from '../sotreKey';
import {
	useSyStemStore
} from './system';
import {
	keyTeam,
	keyUser
} from '../../utils/handleDeptData';


export const useTeamStore = defineStore('useTeamStore', {

	state: () => ({
		teamStoreKey: FormTeamStoreKey,
		formKey: '',
		checkedValue: [],

		copyList: _.cloneDeep(useSyStemStore().teamList),
		list: useSyStemStore().teamList,

	}),
	actions: {
		clearTeamStoreKeyValue(key, value) {
			this.teamStoreKey[key].value = value || []
		},
		delTeamStoreKeyValue(index, key) {
			if (this.teamStoreKey[key].value instanceof Array) {
				this.teamStoreKey[key].value.splice(index, 1)
			}
		},
		setTeamStoreKey(key) {

			if (this.teamStoreKey[key]) {
				this.formKey = key
				this.checkedValue = this.teamStoreKey[key].value
			}
		},
		onClear() {
			this.onChangeKeywords({
				detail: {
					value: ''
				}
			})
		},
		onChangeKeywords: _.debounce(function(e) {
			const {
				value
			} = e.detail

			if (value) {
				const filters = _.filter(this.teamViewListData, (item) => {
					return item.label.indexOf(value) > -1
				})
				this.list = filters
			} else {
				this.list = this.copyList
			}
		}, 500),
		changeData(val) {
			this.teamStoreKey[this.formKey].value = val
		}
	},

	getters: {

		teamViewListData() {
			return _.map(this.list, (item) => {
				return {
					label: item.teamName,
					originValue: item.id,
					value: JSON.stringify({
						key: keyTeam,
						label: item.teamName,
						value: item.id
					}),
					...item
				}
			})

		},

	},
	persist: true
})